from django.shortcuts import render_to_response
from django.core.exceptions import ObjectDoesNotExist
from django.views.decorators.csrf import csrf_exempt

from runtime.utils.msg_tools import get_msg_body
from runtime.users.models import UserProfile
from runtime.utils.msg_tools import render_msg_content
from runtime.utils.msg_tools import get_msg

# Create your views here.
def run(request):
	msg_get = get_msg(request)
	openId = msg_get.FromUserName.text

	url = request.get_host()
	
	url = 'https://' + url + '/useradd/%s' % openId
	print url

	return render_msg_content('text', url)

@csrf_exempt
def useradd(request, openId):
	if request.method == 'POST':
		name = request.POST.get('name')
		openId = request.POST.get('openId')
		stu_id = request.POST.get('stu_id')
		phone = request.POST.get('phone')

		try:
			stu_id = int(stu_id)
		except ValueError:
			stu_id = 000000000000

		new_user = UserProfile(name=name, openId=openId, stu_id=stu_id, phone=phone)
		new_user.save()

	user = get_info(openId)
	return render_to_response('user_register.html', {'openId':openId, 'user':user})

def get_info(openId):
	try:
		user = UserProfile.objects.get(openId=openId)
		return user
	except ObjectDoesNotExist:
		pass